package cn.kgc.ssm.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.kgc.ssm.dto.PageDTO;
import cn.kgc.ssm.entity.SysUser;
import cn.kgc.ssm.entity.User;
import cn.kgc.ssm.mapper.UserMapper;
import cn.kgc.ssm.service.UserService;
import cn.kgc.ssm.util.LayUtil;
import cn.kgc.ssm.vo.SysUserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: mosin
 * @version: v1.0  2022/7/11
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;


    @Override
    public LayUtil findALL(PageDTO pageDTO) {
        //开启分页
        PageHelper.startPage(pageDTO.getPage(), pageDTO.getLimit());

        List<SysUserVO> sysUserVOS = userMapper.selectAll(pageDTO.getUsername());

        //将查询的结果封装成 pageInfo 对象 获取更多的分页参数    total
        PageInfo<SysUserVO> sysUserVOPageInfo = new PageInfo<>(sysUserVOS);
        //获取数据的总条数
        long total = sysUserVOPageInfo.getTotal();

        LayUtil layUtil = new LayUtil();
        layUtil.setCode(0);
        layUtil.setMsg("查询成功");
        layUtil.setData(sysUserVOS);
        layUtil.setCount(total);

        return layUtil;

    }


    @Override
    public Boolean deleteById(Integer id) {
        Integer line =  userMapper.deleteById(id);
        int a = 1/0;
        return line>0;
    }

    @Override
    public Map<String, Object> addUserInfo(SysUser user) {

        Map<String, Object> map = new HashMap<>();

        //根据用户信息查询 账号是否存在  存在 则直接提示用户 用户名不可用
        SysUser usr = userMapper.selectByUserName(user.getUsername());
        System.out.println("user:"+usr);
        if (ObjectUtil.isEmpty(usr)) {  // 用户名可用

            user.setPassword(SecureUtil.md5("123345"));
            Integer line = userMapper.addUser(user);

            if (line > 0) {
                map.put("code", 0);
                map.put("msg", "用户信息添加成功!");
            } else {
                map.put("code", 500);
                map.put("msg", "用户信息添加失败!");
            }

        } else {
            map.put("code", 500);
            map.put("msg", "用户名已被注册!");

        }
        return map;
    }


}
